package com.medata.controller;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.medata.dataObject.*;
import com.medata.exeptions.YunExceptions;
import com.medata.service.DatabaselistService;
import com.medata.service.GlobalsettingService;
import com.medata.service.LogMakeDocumentService;
import com.medata.service.ResserverService;
import com.medata.service.impl.*;
import com.medata.utils.*;
import com.medata.vo.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.xssf.usermodel.*;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.hibernate.engine.spi.SessionImplementor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;

/**
 * @author ：zb
 * @date ：Created in 2019/6/12 0012 11:13
 * @description：
 */
@Controller
@Api
@Slf4j
@RequestMapping("/Auditor")
public class AuditorController {
    @Value("${perfix}")
    private String perfix;
    @Autowired
    private DatabaselistService databaselistService;
    @Autowired
    private GlobalsettingService globalsettingService;
    @Autowired
    private LogMakeDocumentService logMakeDocumentService;
    @Autowired
    private AccountServiceImpl accountService;
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private DocobjectServiceImpl docobjectService;
    @Autowired
    private ResserverService resserverService;
    @Value("${ServerIP}")
    private String ip;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private TemplatefieldsServiceImpl templatefieldsService;
    @Autowired
    private DefaultValueTableServiceImpl defaultValueTableService;
    private Integer nums=160;

    @RequestMapping(value = "/solrSearch/{dbid}/{page}")
    @ResponseBody
    public ModelAndView get_solr_all(@PathVariable String dbid, @PathVariable String page) {
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        Gson gson = new Gson();
        ZlTableVo2 zlTableVo2 = new ZlTableVo2();
        Databaselist databaselist = databaselistService.findByDbid(Integer.valueOf(dbid));
        ModelAndView mv = new ModelAndView();
        //查询suoyinku
        String headXml = SolrXmlUtil.headXml(dbid);
        String returnXml = SolrXmlUtil.returnXml(templatefieldsService, dbid);
        String searchXml = SolrXmlUtil.searchXml(templatefieldsService, Integer.valueOf(dbid), null, null, page);
        String xml = headXml + returnXml + searchXml;
        JsonObject jsonObject = SolrCrudUtil.simp_search(globalsettingService, xml);
        String total = jsonObject.get("total").getAsString();
        int pagesize = 10;
        int pageCount = Integer.valueOf(total) % pagesize == 0 ? Integer.valueOf(total) / pagesize : (Integer.valueOf(total) / pagesize + 1);
        int diffValue = pageCount - Integer.valueOf(page);
        JsonArray docs = jsonObject.get("docs").getAsJsonArray();
        LinkedList<String> colums = new LinkedList<>();
        LinkedList<LinkedList<String>> values = new LinkedList<>();
        int hascolumn = 0;
        for (JsonElement element : docs) {
            SolrReturnBean returnBean = gson.fromJson(element, SolrReturnBean.class);
            LinkedList<String> value = new LinkedList<>();
            LinkedList<SolrReturnBean_Son> fieldlist = returnBean.getField();
            value.add(returnBean.getId());
            for (int x = 0; x < 4; x++) {
                SolrReturnBean_Son field = fieldlist.get(x);
                //20190910
                value.add(XmlUtil.getUnreplace(field.getFieldvalue()));
                if (hascolumn == 0) {
                    colums.add(field.getFielddesc());
                }
            }
            hascolumn = 1;
            for (SolrReturnBean_Son son : fieldlist) {
                if (son.getFieldname().equalsIgnoreCase("createDate")) {
                    String timeValue = son.getFieldvalue();
                    if (timeValue != null && !timeValue.isEmpty()) {
                        timeValue = TimeUtil.getD8Date(timeValue);
                    }
                    value.add(timeValue);
                }
            }
            value.add(fieldlist.get(fieldlist.size() - 2).getFieldvalue());
            String sql = "select ischeck from " + databaselist.getDbname() + " where docid = " + value.get(0);
            try {
                PreparedStatement ps = connection.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    String ischeck = rs.getString(1);
                    value.add(ischeck);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //20190621修改获取ischeck数据
//            value.add(fieldlist.get(fieldlist.size() - 1).getFieldvalue());
            values.add(value);
        }
        colums.add("更新时间");
        colums.add("已上传文件");
        colums.add("是否已通过审核");
        zlTableVo2.setColums(colums);
        zlTableVo2.setValuelist(values);
        List<String> searchFields = SearchFieldUtils.getfield(redisTemplate, dbid);
        mv.addObject("searchList", searchFields);
        mv.addObject("page", Integer.valueOf(page));
        mv.addObject("ZlVo", zlTableVo2);
        mv.addObject("dbid", dbid);
        mv.addObject("dc", databaselist.getDbtitle());
        mv.addObject("dba", databaselist.getDbname());
        mv.addObject("diffValue", diffValue);
        mv.addObject("prePage", Integer.valueOf(page) - 1);
        mv.addObject("pageCount", pageCount);
        mv.addObject("count", total);
        mv.addObject("pageSize", pagesize);
        mv.setViewName("solrTable2");
        mv.addObject("auditor", 1);
        return mv;
    }


    //查看详细内容
    @RequestMapping(value = "/zlupdate/{dbid}/{docid}/{str}", method = RequestMethod.GET)
    public ModelAndView test(@PathVariable Integer dbid, @PathVariable String docid, @PathVariable String str) {
        ModelAndView mv=new ModelAndView();
        String title=null;
        //增加资料信息
        Databaselist databaselist = databaselistService.findByDbid(dbid);
        String sql = "SELECT * from " + databaselist.getDbname() + " where docid=" + docid;
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        String xml = null;
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                title=rs.getString(2);
                xml = rs.getString(3);
            }
        } catch (Exception e) {
            throw new YunExceptions(0, "au修改客户资料时,数据库获取信息异常");
        }
        Map<String,String> valueMap = XmlUtil.getValues(xml, Integer.valueOf(dbid), 100);

        //是否已经录入供应商名单
        if (dbid==16){
            DefaultValueTable vTable = defaultValueTableService.findByDefValuesAndRefId(title, 102);
            if (vTable==null){
                mv.addObject("hasInput","0");
            }else {
                mv.addObject("hasInput","1");
            }
        }else{
            mv.addObject("hasInput","0");
        }
        List<Templatefields> templatefields = templatefieldsService.getByDbidOrderBySequence(dbid);
        List<FieldsVO> fieldsVOS=new ArrayList<>();
        for (Templatefields templatefield:templatefields){
            if (templatefield.getInputType()==0){
                FieldsVO fieldsVO=new FieldsVO();
                fieldsVO.setDesc(templatefield.getTpFieldDesc());
                fieldsVO.setInputType("0");
                fieldsVO.setIsneed(templatefield.getIsNeed());
                fieldsVO.setKey(templatefield.getTpFieldName());
                //添加数据信息
                String fieldDesc = templatefield.getTpFieldDesc();
                String value = DataUtil.getValue(fieldDesc, valueMap);
                fieldsVO.setValue(value);

                fieldsVOS.add(fieldsVO);
            }
            //文本框
            if (templatefield.getInputType()==8){
                FieldsVO fieldsVO=new FieldsVO();
                fieldsVO.setDesc(templatefield.getTpFieldDesc());
                fieldsVO.setInputType("8");
                fieldsVO.setIsneed(templatefield.getIsNeed());
                fieldsVO.setKey(templatefield.getTpFieldName());
                //添加数据信息
                String fieldDesc = templatefield.getTpFieldDesc();
                String value = DataUtil.getValue(fieldDesc, valueMap);
                value=XmlUtil.getUnreplace(value);
                fieldsVO.setValue(value);
                fieldsVOS.add(fieldsVO);
            }
            if (templatefield.getInputType()==2){
                FieldsVO fieldsVO=new FieldsVO();
                fieldsVO.setDesc(templatefield.getTpFieldDesc());
                fieldsVO.setInputType("2");
                fieldsVO.setIsneed(templatefield.getIsNeed());
                fieldsVO.setKey(templatefield.getTpFieldName());
                List<String> values=new ArrayList<>();
                List<DefaultValueTable> tables = defaultValueTableService.findByRefId(templatefield.getRefId());
                for (DefaultValueTable table:tables){
                    values.add(table.getDefValues());
                }
                fieldsVO.setValuelist(values);
                //添加数据信息
                String fieldDesc = templatefield.getTpFieldDesc();
                String value = DataUtil.getValue(fieldDesc, valueMap);
                fieldsVO.setValue(value);

                fieldsVOS.add(fieldsVO);
            }
            if (templatefield.getInputType()==4|templatefield.getInputType()==7){
                FieldsVO fieldsVO=new FieldsVO();
                fieldsVO.setDesc(templatefield.getTpFieldDesc());
                fieldsVO.setInputType(String.valueOf(templatefield.getInputType()));
                fieldsVO.setKey(templatefield.getTpFieldName());
                fieldsVO.setIsneed(templatefield.getIsNeed());
                //添加数据信息
                if (templatefield.getInputType()==4){
                    String fieldDesc = templatefield.getTpFieldDesc();
                    String value = DataUtil.getValue(fieldDesc, valueMap);
                    fieldsVO.setValue(value);
                }else{
                    String fieldDesc = templatefield.getTpFieldDesc();
                    String value = DataUtil.getValue(fieldDesc, valueMap);
                    String[] values = value.split(",");
                    List<String> list = Arrays.asList(values);
                    fieldsVO.setValues(list);
                }
                fieldsVOS.add(fieldsVO);
            }
        }
        String[] split = str.split("@");
        if (split.length == 2) {
            mv.addObject("ss", split[0]);
            mv.addObject("page", split[1]);
        } else {
            mv.addObject("page", split[0]);
        }

        mv.addObject("fieldsVOS",fieldsVOS);
        mv.setViewName("zlUpdateForm");
        mv.addObject("dc", databaselist.getDbtitle());
        mv.addObject("dbid", dbid);
        //添加文件信息
        List<Docobject> docLists = docobjectService.findByDocidAndDbid(docid, String.valueOf(dbid));
        mv.addObject("docLists", docLists);
        mv.addObject("auditor",1);
        return mv;
    }

    //单文件下载
    @RequestMapping(value = "fileDown/{objId}")
    public void fileDwon(HttpServletResponse response, @PathVariable String objId) {
        Resserver resserver = resserverService.findByServerport("6896");
        String filePath=resserver.getRespath();
        try {
            Docobject objectid = docobjectService.findAllByObjectid(objId);
            String path = objectid.getServerfullpath();
            Databaselist databaselist = databaselistService.findByDbid(Integer.valueOf(objectid.getDbid()));
            String dbaname=databaselist.getDbname();
            File file = new File(filePath + "/" + dbaname + "/" + path);
            String tempPath = filePath + "/tempFiles/" + dbaname + "/" + UidUtil.getUid() + "/" + objectid.getObjectfilename();
            File tempfile = new File(tempPath);
            FileUtils.copyFile(file, tempfile);
            String filename = objectid.getObjectfilename();
            response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
            FileCopyUtils.copy(new FileInputStream(tempfile), response.getOutputStream());
        } catch (Exception e) {
            try {
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.print("<script type='text/javascript'>alert('文件资源异常,请联系管理员');history.go(-1)</script>");
                writer.flush();
                writer.close();
            } catch (Exception e1) {
                throw new YunExceptions(0, "下载单个文件的时候,资源异常");
            }
        }
        return;
    }

    //文件在线预览
    @RequestMapping(value = "fileOpen/{objid}", method = RequestMethod.GET)
    public ModelAndView fileOpen(@PathVariable String objid, HttpServletResponse response) {
        Resserver resserver = resserverService.findByServerport("6896");
        String filePath=resserver.getRespath();
        ModelAndView mv=new ModelAndView();
        Docobject docobject = docobjectService.findAllByObjectid(objid);
        String filename=docobject.getObjectfilename();
        String uid = UidUtil.getUid();
        Databaselist databaselist = databaselistService.findByDbid(Integer.valueOf(docobject.getDbid()));
        String dbaname=databaselist.getDbname();
        String tempPath = filePath + "/tempFiles/"+dbaname+"/"+uid;
        File tempFile = new File(tempPath);
        if (!tempFile.exists()) {
            tempFile.mkdirs();
        }
        File file1 = new File(filePath+"/"+dbaname+"/"+docobject.getServerfullpath());
        filename=filename.replaceAll("%","");
        String newName = tempPath + "/" + filename;
        File file2 = new File(newName);
        if (filename.endsWith(".pdf")){
            try {
                FileUtils.copyFile(file1, file2);
                String url=ip +perfix+ "/pdfjs/web/viewer.html?file="+ip+perfix+"/tempFiles/"+dbaname+"/"+uid+"/"+filename;
                mv.addObject("pdfname",docobject.getObjectfilename());
                mv.addObject("pdfurl",url);
                long length = file2.length();
                long c=10485760;
                long time = length / c;
                time=time*1000+1000;
                mv.addObject("waitTime",time);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mv.setViewName("pdfview");
            return mv;
        }else {
            InputStream is=null;
            OutputStream os=null;
            try {
                response.setContentType("image/jpeg");
                FileUtils.copyFile(file1, file2);
                response.addHeader("Content-Length", "" + file2.length());
                is=new FileInputStream(file2);
                os=response.getOutputStream();
                IOUtils.copy(is,os);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    if (os!=null){
                        os.flush();
                        os.close();
                    }
                    if (is!=null){
                        is.close();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    throw new YunExceptions(0,"浏览图偏,关闭流bug");
                }
            }
            return null;
        }
    }

    //获取solr搜索结果
    @RequestMapping(value = "solrSearch/{dbid}/{word}/{str}/{page}", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView getObjects(@PathVariable String dbid, @PathVariable String word, @PathVariable String str, @PathVariable String page) {
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        Gson gson = new Gson();
        ZlTableVo2 zlTableVo2 = new ZlTableVo2();
        Databaselist databaselist = databaselistService.findByDbid(Integer.valueOf(dbid));
        ModelAndView mv = new ModelAndView();
        //是否有获取资料权限
//        Integer hasAuthority = AuthorityUtil.hasAuthority(accountService, String.valueOf(dbid));
//        if (hasAuthority == 0) {
//            throw new UnauthorizedException();
//        }
        //查询suoyinku
        String headXml = SolrXmlUtil.headXml(dbid);
        String returnXml = SolrXmlUtil.returnXml(templatefieldsService, dbid);
        String searchXml = SolrXmlUtil.searchXml(templatefieldsService, Integer.valueOf(dbid), word, str, page);
        String xml = headXml + returnXml + searchXml;
        JsonObject jsonObject = SolrCrudUtil.simp_search(globalsettingService, xml);
        String total = jsonObject.get("total").getAsString();
        int pagesize = 10;
        int pageCount = Integer.valueOf(total) % pagesize == 0 ? Integer.valueOf(total) / pagesize : (Integer.valueOf(total) / pagesize + 1);
        int diffValue = pageCount - Integer.valueOf(page);
        JsonArray docs = jsonObject.get("docs").getAsJsonArray();
        LinkedList<String> colums = new LinkedList<>();
        LinkedList<LinkedList<String>> values = new LinkedList<>();
        int hascolumn = 0;
        for (JsonElement element : docs) {
            SolrReturnBean returnBean = gson.fromJson(element, SolrReturnBean.class);
            LinkedList<String> value = new LinkedList<>();
            LinkedList<SolrReturnBean_Son> fieldlist = returnBean.getField();
            value.add(returnBean.getId());
            for (int x = 0; x < 4; x++) {
                SolrReturnBean_Son field = fieldlist.get(x);
                //修复显示特殊字符的bug
                value.add(XmlUtil.getUnreplace(field.getFieldvalue()));
                if (hascolumn == 0) {
                    colums.add(field.getFielddesc());
                }
            }
            hascolumn = 1;
            for (SolrReturnBean_Son son : fieldlist) {
                if (son.getFieldname().equalsIgnoreCase("createDate")) {
                    String timeValue = son.getFieldvalue();
                    if (timeValue != null && !timeValue.isEmpty()) {
                        timeValue = TimeUtil.getD8Date(timeValue);
                    }
                    value.add(timeValue);
                }
            }
            value.add(fieldlist.get(fieldlist.size() - 2).getFieldvalue());
            String sql = "select ischeck from " + databaselist.getDbname() + " where docid = " + value.get(0);
            try {
                PreparedStatement ps = connection.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    String ischeck = rs.getString(1);
                    value.add(ischeck);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new YunExceptions(0, "solr获取分页数据的时候,查询数据库出错");
            }
            //20190621更改审核信息
//            value.add(fieldlist.get(fieldlist.size() - 1).getFieldvalue());
            values.add(value);
        }
        colums.add("更新时间");
        colums.add("已上传文件");
        colums.add("是否已通过审核");
        zlTableVo2.setColums(colums);
        zlTableVo2.setValuelist(values);
        List<String> searchFields = SearchFieldUtils.getfield(redisTemplate, dbid);
        mv.addObject("searchList", searchFields);
        mv.addObject("page", Integer.valueOf(page));
        mv.addObject("str", str);
        mv.addObject("ZlVo", zlTableVo2);
        mv.addObject("dbid", dbid);
        mv.addObject("dc", databaselist.getDbtitle());
        mv.addObject("dba", databaselist.getDbname());
        mv.addObject("diffValue", diffValue);
        mv.addObject("prePage", Integer.valueOf(page) - 1);
        mv.addObject("pageCount", pageCount);
        mv.addObject("count", total);
        mv.addObject("pageSize", pagesize);
        mv.setViewName("solrTable2");
        mv.addObject("word", word);
        mv.addObject("auditor", 1);
        return mv;
    }
    //审核
    @RequestMapping(value = "/audit", method = RequestMethod.POST)
    public void zlrefuse(HttpServletResponse response, String docid,Integer dbid,String flag) {
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        Databaselist databaselist = databaselistService.findByDbid(dbid);
        String sql="update "+databaselist.getDbname()+" set isCheck = ? where docid = ?";
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,flag);
            ps.setString(2,docid);
            ps.execute();
            SolrUtils.updateIndex(globalsettingService,dbid,databaselist.getDbname(),0,docid);
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.print("<script type='text/javascript'>alert('操作成功');history.go(-2);self.parent.$('#checkChange').val('1')</script>");
            writer.flush();
            writer.close();


        }catch (Exception e){
            e.printStackTrace();
            throw new YunExceptions(0,"通过审核出现bug");
        }
    }

    //导出信息
    @RequestMapping(value = "ExcelGet/{dbid}", method = RequestMethod.GET)
    public HttpServletResponse getExcel(HttpServletResponse response, @PathVariable Integer dbid) {
        try {
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet1 = workbook.createSheet();
            XSSFSheet sheet2 = workbook.createSheet();
            Databaselist databaselist = databaselistService.findByDbid(dbid);
            String filename = databaselist.getDbtitle();
            String sql = "select * from  " + databaselist.getDbname() + " where ischeck = 0 ORDER BY CreateDate desc";
            String sql2 = "select * from  " + databaselist.getDbname() + " where ischeck = 1 ORDER BY CreateDate desc";
            SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
            Connection connection = session.connection();
            List<List<String>> values = new ArrayList<>();
            List<String> keys = new ArrayList<>();
            List<String> keys2 = new ArrayList<>();
            List<List<String>> values2 = new ArrayList<>();
            int haskey = 0;
            PreparedStatement ps = connection.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                List<String> value = new ArrayList<>();
                String xml = rs.getString(3);
                Document document = DocumentHelper.parseText(xml);
                Element root = document.getRootElement();
                List<Element> list = root.elements();
                for (Element e : list) {
                    String text = e.getText();
                    value.add(text);
                    if (haskey == 0) {
                        String name = e.attributeValue("FieldDesc");
                        keys.add(name);
                    }
                }
                haskey = 1;
                value.add(rs.getString(6));
                value.add(rs.getString(7));
                value.add("等待审核");
                values.add(value);
            }

            int haskey2 = 0;
            PreparedStatement ps2 = connection.prepareStatement(sql2);
            ResultSet rs2 = ps2.executeQuery();
            while (rs2.next()) {
                List<String> value = new ArrayList<>();
                String xml = rs2.getString(3);
                System.out.println(rs2.getString(1));
                xml=xml.replaceAll("&#","");
                Document document = DocumentHelper.parseText(xml);
                Element root = document.getRootElement();
                List<Element> list = root.elements();
                for (Element e : list) {
                    String text = e.getText();
                    value.add(text);
                    if (haskey2 == 0) {
                        String name = e.attributeValue("FieldDesc");
                        keys2.add(name);
                    }
                }
                haskey2 = 1;
                value.add(rs2.getString(6));
                value.add(rs2.getString(7));
                value.add("通过审核");
                values2.add(value);
            }

            keys = keys.size() > keys2.size() ? keys : keys2;
            keys.add("编辑人员ID");
            keys.add("更新时间");
            keys.add("是否过审");
            String[] headers = keys.toArray(new String[keys.size()]);
            sheet1.setDefaultColumnWidth(1000);
            sheet2.setDefaultColumnWidth(1000);
            XSSFRow row1 = sheet1.createRow(0);
            XSSFRow row2 = sheet2.createRow(0);

            //将表头信息放入第一行
            for (int i = 0; i < headers.length; i++) {
                XSSFCell cell = row1.createCell(i);
                XSSFRichTextString text = new XSSFRichTextString(headers[i]);
                cell.setCellValue(text);
            }
            int rowNum = 1;
            for (List<String> va : values) {
                XSSFRow row = sheet1.createRow(rowNum);
                for (int x = 0; x < va.size(); x++) {
                    row.createCell(x).setCellValue(va.get(x));
                }
                rowNum++;
            }

            //将表头信息放入第一行
            for (int i = 0; i < headers.length; i++) {
                XSSFCell cell = row2.createCell(i);
                XSSFRichTextString text = new XSSFRichTextString(headers[i]);
                cell.setCellValue(text);
            }
            int rowNum2 = 1;
            for (List<String> va : values2) {
                XSSFRow row = sheet2.createRow(rowNum2);
                for (int x = 0; x < va.size(); x++) {
                    row.createCell(x).setCellValue(va.get(x));
                }
                rowNum2++;
            }
            response.setContentType("application/vnd.ms-excel");
            //解决下载名中文乱码问题第二步
            response.setHeader("Content-Disposition", "attachment; filename=" + new String(filename.getBytes("gbk"), "iso8859-1") + ".xlsx");

            response.flushBuffer();
            workbook.write(response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
            throw new YunExceptions(0, "导出信息的时候出现bug");
        }
        return null;
    }

    //删除原始索引数据
    @RequestMapping(value = "/solrDelete/{dbid}", method = RequestMethod.GET)
    @ResponseBody
    public void solrDelete(@PathVariable Integer dbid) {
        Databaselist databaselist = databaselistService.findByDbid(dbid);
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
            String sql="select docid from "+databaselist.getDbname()+" where IndexFlag =1";
            Connection connection = session.connection();
            try {
                PreparedStatement ps = connection.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();
                String dcid=null;
                while (rs.next()){
                    dcid = rs.getString(1);
                    if (dcid!=null){
                        SolrUtils.deleteIndex(globalsettingService,databaselist.getDbname(),dcid);
                        String sql2="update "+databaselist.getDbname()+" set IndexFlag = 0 where docid = " + dcid;
                        PreparedStatement ps2 = connection.prepareStatement(sql2);
                        ps2.execute();
                    }
                }
                nums--;
            }catch (Exception e){
                e.printStackTrace();
                throw new YunExceptions(0,"更新索引的时候出现bug");
            }
//        }
    }

    //更新检索数据2
    @RequestMapping(value = "/solrUpdate/{dbid}", method = RequestMethod.GET)
    public void solrUpdate2(@PathVariable Integer dbid, HttpServletResponse response) {
        Databaselist databaselist = databaselistService.findByDbid(dbid);
        SolrUtils.insertAllIndexs(globalsettingService,databaselist.getDbname(),dbid);
        String sql="update "+databaselist.getDbname()+" set indexFlag= '1' where indexFlag= '0'";
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        try {
            Statement statement = connection.createStatement();
            statement.execute(sql);
            statement.close();
            connection.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    //xml在线预览
    @RequestMapping(value = "fileOpen/{objid}/xml", method = RequestMethod.GET)
    @ResponseBody
    public List<String> fileOpen2(@PathVariable String objid, HttpServletResponse response) {
        Resserver resserver = resserverService.findByServerport("6896");
        String filePath=resserver.getRespath();
        Docobject docobject = docobjectService.findAllByObjectid(objid);
        Databaselist databaselist = databaselistService.findByDbid(Integer.valueOf(docobject.getDbid()));
        String dbaname=databaselist.getDbname();
        File file = new File(filePath + "/" + dbaname + "/" + docobject.getServerfullpath());
        try {
            List<String> list = FileUtils.readLines(file, "utf-8");
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
